import cv2 as cv
import numpy as np
import torch
import torchvision.transforms as transforms

# 读取图像
img = cv.imread("C:/111.jpg")

# 检查图像是否成功加载
if img is None:
    raise FileNotFoundError("图像路径错误或图像未找到！")

# 将 BGR 转换为 RGB
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)

# 打印图像类型和形状
print("图像类型:", type(img))  # <class 'numpy.ndarray'>
print("图像形状:", img.shape)  # (H, W, C)

# 将 NumPy 数组转换为 PyTorch 张量
transf = transforms.ToTensor()
img_tensor = transf(img)

# 打印张量的形状
print("张量形状:", img_tensor.size())  # (C, H, W)

# 添加批量维度
img_tensor = img_tensor.unsqueeze(0)  # 形状变为 (1, C, H, W)

# 创建卷积层，输入通道数为 3，输出通道数为 3，卷积核大小为 5
max_pool = torch.nn.Conv2d(3, 3, 5)
max_pool1 = torch.nn.MaxPool2d(15)
# 进行卷积操作
result = max_pool(img_tensor)
result = max_pool(result)
result = max_pool1(result)
# 打印卷积结果的形状
print("卷积结果形状:", result.size())  # (N, C, H_out, W_out)

# 将 Tensor 转换为 NumPy 数组
numpy_image = result.squeeze(0).detach().numpy()  # 去掉批量维度
# 调整通道顺序：从 (C, H, W) 到 (H, W, C)
numpy_image = np.transpose(numpy_image, (1, 2, 0))
# 将 BGR 转换为 RGB
numpy_image = (numpy_image * 255).astype(np.uint8)

# 显示图像
cv.imshow("卷积结果", numpy_image)
cv.waitKey(0)
cv.destroyAllWindows()